<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import CdlDescriptions from "@/components/descriptions";
import CdlBill from "@/components/bill"
import {createPopup} from "@/utils/createPopup";
import {Project} from "@/interfaces/views/project/project";
import {DescriptionsTree} from "@/interfaces/components/Descriptions";
import {computed, ref, h} from "vue"
import {useProjectInfoApi} from "@/api/project/project";
import CdlTable from "@/components/table";
import {FormData, Mode} from "@/interfaces/components/Page"
import {TableTree} from "@/interfaces/components/Table";
import {Task, WayBill} from "@/interfaces/views/task/task";
import {Information} from "@/interfaces/views/project/information";
import Step from "@/views/projectManage/project/projectList/step.vue";
import {mergeObjects} from "@/utils/utilities";
import {Bills} from "@/interfaces/views/finance/bills";
import {useCreateBillInsertApi, useProjectBillListApi} from "@/api/finance/finance";
import {ElMessage} from "element-plus/es";

const router = useRouter()
const route = useRoute()
const loading = ref(true)
if(route.query.id) init()

const baseDescriptionsTree: DescriptionsTree<Project> = [
    {label: "订单名称", prop: "name"},
    {label: "订单类型", prop: "typeId", dict: "project_type"},
    {label: "订单负责人", prop: "managerName"},
    {label: "托运人", prop: "shipperName"},
    {label: "托运人法人名称", prop: "legalPerson"},
    {label: "托运人信用代码", prop: "idNum"},
    {label: "货物名称", prop: "cargoName"},
    {label: "货物毛重", prop: "cargoGrossWeight"},
    {label: "货物分类代码", prop: "cargoTypeId"},
    {label: "装货地址", prop: "loadingAddress"},
    {label: "卸货地址", prop: "unloadingAddress"},
    {label: "订单预估完成日期", prop: "expectedTime"},
]
const billTableTree: TableTree<Bills> = {
  colRule: [
    {ti: "账单ID", prop: "id", width: 180},
    {ti: "账单名称", prop: "billTypeName"},
    {ti: "收入/支出", prop: "modeId", dict: "bill_mode", width: 130},
    {ti: "收款人名称", prop: "gatherName"},
    {ti: "付款人名称", prop: "paypalName"},
    {ti: "金额", prop: "amount"},
    {ti: "账单说明", prop: "billRemark"},
    {ti: "交易单号", prop: "transNo", width: 150},
    {ti: "支付方式", prop: "payWay"},
    {ti: "图片", prop: "imageArr"},
    {ti: "状态", prop: "billStatus", dict: "bill_status"},
    {ti: "处理意见", prop: "handleMsg", tooltip: true},
    {ti: "备注", prop: "remark", tooltip: true},
  ]
}
const taskTableTree: TableTree<Task> = {
  colRule: [
    {ti: "任务名称", prop: "name"},
    {ti: "关联司机", prop: "cars", slot: (val)=>{
        return h("span", val.length + "人")
      }},
    {ti: "任务状态", prop: "state", dict: "task_state"},
    {ti: "开始日期", prop: "startTime", minWidth: 160},
    {ti: "结束日期", prop: "endTime", minWidth: 160},
    {ti: "运单数", prop: "waybills", format: (scope: WayBill[]) =>{
        return scope.length.toString()
      }},
    {ti: "创建人", prop: "create"},
    {ti: "备注", prop: "remark"},
  ],
  control: [
    {name: "详情", type: "primary", prop: "id", method: jumpTaskInfo}
  ]
}

const extraDescriptionsTree: DescriptionsTree<Information> = [
  {label: "保险公司", prop: "insurance"},
  {label: "保险单号", prop: "insuranceSn"},
  {label: "备注", prop: "remark"},
]

const baseData = ref<FormData<Project>>({
  id: "",
  name: "",
  typeId: "",
  managerName: "",
  shipperName: "",
  legalPerson: "",
  idNum: "",
  cargoName: "",
  cargoGrossWeight: undefined,
  cargoTypeId: undefined,
  loadingAddress: "",
  unloadingAddress: "",
  expectedTime: "",
  projectStatus: 1,
  payMode: undefined
})
const billData = ref<Bills[]>([])
const taskData = ref([])
const extraData = ref<FormData<Project>>({
  insurance: "",
  insuranceSn: ""
})

const isOrderAdvanceChargeType = computed(()=>{
  return baseData.value.payMode === 1
})
const stepStatus = computed(()=> {
  if(!baseData.value.payMode) return 0
  return baseData.value.projectStatus! - 2
})

/**
 * 初始化
 */
function init(){
  useProjectInfoApi(route.query.id as string).then(res =>{
    const {taskList, insurance, insuranceSn, ...rest} = res.data
    mergeObjects(baseData.value, rest)
    taskData.value = taskList
    extraData.value.insurance = insurance
    extraData.value.insuranceSn = insuranceSn
    loading.value = false
  })
  getBillList()
}
const advancePaymentBill = ref(false)
const finalPaymentStatement = ref(false)
function getBillList(){
  useProjectBillListApi(route.query.id as string).then(res =>{
    billData.value = res.data
    const advance = res.data.filter((item: Bills) => item.billTypeId === "1" && item.billStatus !== 2)
    const final = res.data.filter((item: Bills) => item.billTypeId === "3" && item.billStatus !== 2)
    console.log(final)
    advancePaymentBill.value = advance.length && advance.find((item: Bills) => item.billStatus !== 2)
    finalPaymentStatement.value = final.length && final.find((item: Bills) => item.billStatus !== 2)
  })
}
function jumpProjectUpdate(){
  router.push({
    path: "/projectManage/project/projectList/createAndModifyProject",
    query: {
      id: route.query.id
    }
  })
}
function jumpTaskInfo(id: string){
  router.push({
    path: "/projectManage/task/taskDetails",
    query: {
      id: id
    }
  })
}

/**
 * 跳转新建任务
 */
function jumpCreateTask(){
  router.push({
    path: "/projectManage/task/createAndModifyTask",
    query: {
      projectId: route.query.id,
      cargoName: baseData.value.cargoName,
      cargoType: baseData.value.cargoTypeId
    }
  })
}

/**
 * 创建预付款
 */
function openCreateAdvanceCharge(){
  createPopup("新建预付款账单", h(CdlBill, {
    types: [2],
    init: "预付款"
  }), "add", popupCallBack)
}

/**
 * 创建尾款
 */
function openCreateBalancePayment(){
  createPopup("新建尾款账单", h(CdlBill, {
    types: [2],
    init: "尾款"
  }), "add", popupCallBack)
}
function popupCallBack(mode: Mode, data: Bills){
  data.billId = route.query.id as string
  data.billName = baseData.value.name!
  useCreateBillInsertApi(data).then(() =>{
    ElMessage.success("创建成功")
    getBillList()
  })
}

/**
 * 回退页面
 */
function fallbackPage(){
  router.back()
}
</script>

<template>
<el-card v-if="loading"><el-skeleton :rows="5" animated /></el-card>
<el-card v-else style="position: relative">
  <button class="back_btn" @click="fallbackPage"></button>
  <div class="main_control">
    <el-button v-if="baseData.projectStatus !== 1" type="success" @click="jumpProjectUpdate" v-auth="'project:project:update'">编辑</el-button>
    <el-button v-if="baseData.projectStatus < 5 && isOrderAdvanceChargeType && !advancePaymentBill"
               type="primary" @click="openCreateAdvanceCharge">创建预付款</el-button>
    <el-button v-if="baseData.projectStatus < 5 && !finalPaymentStatement"
               type="primary" @click="openCreateBalancePayment">创建尾款</el-button>
    <el-button v-if="![1, 5, 6].includes(baseData.projectStatus as number)"
               type="primary" @click="jumpCreateTask" v-auth="'project:project:sell'">派发任务</el-button>
    <el-button v-if="baseData.projectStatus === 5" type="danger" v-auth="'project:project:end'">结束订单</el-button>
  </div>
  <Step class="step" v-if="baseData.payMode" :mode="baseData.payMode" :state="stepStatus"></Step>
  <h1 class="top_line" style="margin-top: 15px">基础信息</h1>
  <el-divider></el-divider>
  <CdlDescriptions :model="baseData" :template-tree="baseDescriptionsTree"></CdlDescriptions>
  <div v-if="billData.length">
    <h1 class="top_line" style="margin-top: 15px">账单信息</h1>
    <el-divider></el-divider>
    <CdlTable :data="billData" :template-tree="billTableTree"></CdlTable>
  </div>
  <div v-if="baseData.projectStatus !== 2">
    <h1 class="mgt">任务列表</h1>
    <el-divider></el-divider>
    <CdlTable :data="taskData" :template-tree="taskTableTree"></CdlTable>
  </div>
  <h1 class="mgt">其他附加信息</h1>
  <el-divider></el-divider>
  <CdlDescriptions :model="extraData" :template-tree="extraDescriptionsTree"></CdlDescriptions>
</el-card>
</template>

<style scoped>
.step{
  position: absolute;
  top: 8px;
  left: 150px;
  width: 800px;
}
>>>.el-step__main{
  display: flex;
  align-items: center;
  margin-top: 8px;
}
>>>.el-step__title{
  line-height: normal;
}
>>>.el-step__description{
  line-height: normal;
  margin: 0 0 0 10px;
  padding: 0;
}
</style>
